<template>
  <div id="body">
    <el-tabs v-model="activeTab" @tab-click="tabClick">
      <el-tab-pane label="概况" name="summary" class="padding-top-25px">

        <el-row type="flex" class="row-bg">
          <el-col :span="18">
            <div class="grid-content bg-purple">
              <h1>概况</h1>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple">
              <el-date-picker
                v-model="params.dateRange"
                type="daterange"
                @change="fillBaseSummary"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table :data="summary.table.data" stripe style="width: 100%">
              <el-table-column prop="schoolName" label="基地"></el-table-column>
              <el-table-column prop="practice" label="实践数"></el-table-column>
              <el-table-column prop="address" label="地址"></el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="15">
            <el-pagination class="margin-top-20" @current-change="currentChange" background layout="prev, pager, next" :current-page="summary.page.currentPage" :total="summary.page.total">
            </el-pagination>
          </el-col>
        </el-row>

      </el-tab-pane>

      <el-tab-pane label="实践统计" name="practice" class="padding-top-25px">

        <el-row>
          <el-col :span="12">
            <h1>检索</h1>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="fillPractice">查询</el-button>
          </el-col>
          <el-col :span="4">
            <el-select v-model="curtOid" clearable filterable placeholder="全部">
              <el-option v-for="item in schools.data" :key="item.oid" :label="item.name" :value="item.oid">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4" style="margin-left: 20px">
            <el-date-picker v-model="params.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table v-loading="practice.table.loading" :data="practice.table.data" stripe style="width: 100%">
              <el-table-column prop="dateStr" label="日期">
              </el-table-column>
              <el-table-column prop="practiceCount" label="实践数">
              </el-table-column>
              <el-table-column prop="checkInCount" label="签到">
              </el-table-column>
              <el-table-column prop="notSignCount" label="未签到">
              </el-table-column>
              <el-table-column prop="absenceCount" label="缺勤">
              </el-table-column>
              <el-table-column prop="patchCount" label="补签">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showPracticeDetails(scope.row.date)" type="text" size="small">查看记录</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-dialog title="签到详情" :visible.sync="practice.table.detailsVisible" :fullscreen="true">
            <h1 style="margin-bottom: 20px">{{ detailsViewDate }}</h1>
            <el-input placeholder="请输入名称" style="margin-bottom: 20px" v-model="practice.table.filterDetails"></el-input>
            <el-table :data="practice.table.detailsTableData" :row-class-name="detailsTableClassName">
              <el-table-column property="date" label="日期"></el-table-column>
              <el-table-column width="120px" property="name" label="名字"></el-table-column>
              <el-table-column width="120px" property="isTeam" label="团队/个人"></el-table-column>
              <el-table-column width="120px" property="leaderName" label="带队人"></el-table-column>
              <el-table-column width="80px" property="role" label="角色"></el-table-column>
              <el-table-column property="oname" label="学校"></el-table-column>
              <el-table-column property="className" label="班级"></el-table-column>
              <el-table-column width="300px" property="baseName" label="基地"></el-table-column>
              <el-table-column width="100px" property="type" label="操作类型"></el-table-column>
              <el-table-column width="80px" property="status" label="状态"></el-table-column>
              <el-table-column property="signTime" label="签到时间"></el-table-column>
              <el-table-column property="patchTime" label="补签时间"></el-table-column>
            </el-table>

          </el-dialog>

        </el-row>
      </el-tab-pane>

      <el-tab-pane label="预约统计" name="reservation" class="padding-top-25px">
        <el-row>
          <el-col :span="12">
            <h1>预约</h1>
          </el-col>

          <el-col :span="2">
            <el-button type="primary" @click="fillReservation">查询</el-button>
          </el-col>

          <el-col :span="4">
            <el-select v-model="curtOid" clearable filterable placeholder="全部">
              <el-option v-for="item in schools.data" :key="item.oid" :label="item.name" :value="item.oid"></el-option>
            </el-select>
          </el-col>

          <el-col :span="4" style="margin-left: 20px">
            <el-date-picker v-model="params.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table v-loading="reservation.table.loading" :data="reservation.table.data" stripe style="width: 100%">
              <el-table-column prop="dateStr" label="日期"></el-table-column>
              <el-table-column prop="total" label="总计"></el-table-column>
              <el-table-column prop="teacherCount" label="教师预约"></el-table-column>
              <el-table-column prop="studentCount" label="学生预约"></el-table-column>
              <el-table-column prop="cancelCount" label="取消"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showReservationDetailsByDay(scope.row.date)" type="text" size="small">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <!--按天详情-->
        <el-dialog title="详情" :visible.sync="reservation.table.detailsVisible" :fullscreen="true">
          <h1 style="margin-bottom: 20px">{{ detailsReservationViewDate }}</h1>
          <el-table :data="reservation.table.detailsTableData">
            <el-table-column width="180px" property="reservationId" label="预约编号"></el-table-column>
            <el-table-column width="120px" property="leaderName" label="带队人"></el-table-column>
            <el-table-column width="120px" property="isTeam" label="团队/个人"></el-table-column>
            <el-table-column width="80px" property="role" label="角色"></el-table-column>
            <el-table-column property="schoolName" label="学校"></el-table-column>
            <el-table-column property="className" label="班级"></el-table-column>
            <el-table-column width="300px" property="baseName" label="基地"></el-table-column>
            <el-table-column width="80px" property="count" label="团队成员"></el-table-column>
            <el-table-column width="80px" property="status" label="状态"></el-table-column>
            <el-table-column property="startTime" label="开始时间"></el-table-column>
            <el-table-column property="endTime" label="结束时间"></el-table-column>
            <el-table-column property="createdAt" label="发起时间"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showReservationDetails(scope.row.reservationId)" type="text" size="small">预约详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>

        <el-dialog title="预约详情" :visible.sync="reservation.details.detailsVisible" :fullscreen="true">
          <el-table :data="reservation.details.data">
            <el-table-column width="160px" property="account" label="账号"></el-table-column>
            <el-table-column width="120px" property="name" label="名字"></el-table-column>
            <el-table-column width="80px" property="role" label="角色"></el-table-column>
            <el-table-column property="schoolName" label="学校"></el-table-column>
            <el-table-column property="className" label="班级"></el-table-column>
            <el-table-column property="signInStatus" label="签到状态"></el-table-column>
            <el-table-column property="signOutStatus" label="签退状态"></el-table-column>
            <el-table-column property="signInTime" label="签到时间"></el-table-column>
            <el-table-column property="signOutTime" label="签退时间"></el-table-column>
            <el-table-column property="patchInTime" label="签到补签时间"></el-table-column>
            <el-table-column property="patchOutTime" label="签退补签时间"></el-table-column>
          </el-table>
        </el-dialog>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import { getBaseSummary, getSchoolSummary, getSchoolByAreaCodes, getPracticeByDate, getSignRecordsByDay, getReservationStatistics, getReservationDetails, getTeamsByReservationId } from '../../../../api/feizns/statistics/index'
  import { getDays, getRole, getSignStatus, getSignType, toYMD, toYMD_HM, getReservationStatus } from '../../../../utils/feizns'
  import config from '../../../../plugin/axios/config'

  export default {
    name: 'SchoolStatistics',
    data() {
      return {
        userAreaCodes: JSON.parse(sessionStorage.getItem('user')).areaCode,
        activeTab: 'summary',
        tabLoading: {
          summary: {
            isLoading: true,
            func: this.fillBaseSummary
          },
          practice: {
            isLoading: false,
            func: () => {
              this.fillSchool()
              this.fillPractice()
            }
          },
          reservation: {
            isLoading: false,
            func: () => {
              this.fillSchool()
              this.fillReservation();
            }
          }
        },

        params: {
          dateRange:[new Date(new Date() - (1000 * 60 * 60 * 24 * 30)), new Date()]
        },

        curtOid: null,

        summary: {
          table: {
            data:[]
          },
          page: {
            currentPage: 1,
            total: 0,
            pageSize: 10
          }
        },

        practice: {
          table: {
            loading: false,
            data: [],
            detailsVisible: false,
            detailsViewDate: null,
            detailsTableData: [],
            detailsOriginalData: [],
            filterDetails:''
          },
        },

        reservation: {
          table: {
            loading: false,
            data: [],
            detailsVisible: false,
            detailsViewDate: null,
            detailsTableData: [],
          },
          details: {
            data:[],
            detailsVisible: false
          }
        },

        schools: {
          data:[],
        }
      }
    },

    computed: {
      detailsViewDate: function() {
        return toYMD(this.practice.table.detailsViewDate);
      },
      detailsReservationViewDate: function () {
        return toYMD(this.reservation.table.detailsViewDate);
      }
    },

    watch: {
      'practice.table.filterDetails': function (n) {
        this.practice.table.detailsTableData = this.practice.table.detailsOriginalData
          .filter(item => {
            for (const k in item) {
              if ( typeof item[k] == 'string' && item[k].indexOf(n) != -1 )
                return true;
            }
            return false;
          });
      }
    },

    methods: {
      detailsTableClassName(e) {
        return e.row.stripe ? '' : 'f2f6fc';
      },

      tabClick(tab) {
        let tmp = this.tabLoading[tab.name];
        if ( tmp && tmp.isLoading == false ) {
          tmp.func();
          tmp.isLoading = true;
        }
      },

      currentChange(val) {
        this.summary.page.currentPage = val;
        this.fillBaseSummary();
      },

      showPracticeDetails(date) {
        this.practice.table.detailsVisible = true;
        this.practice.table.detailsViewDate = date;

        let params = {
          date: new Date(date).toJSON(),
          oid: this.curtOid,
          schoolAreas: this.userAreaCodes
        }

        this.practice.table.detailsTableData = [];
        getSignRecordsByDay(params).then(resp => {
          let prev;
          let stripe = true;
          this.practice.table.detailsOriginalData = resp.data;
          resp.data.forEach(item => {
            item.date = toYMD_HM(item.date);
            item.signTime = toYMD_HM(item.signTime);
            item.patchTime = toYMD_HM(item.patchTime);
            item.isTeam = (item.role == 'student' && (item.name == item.leaderName)) ? '个人' : '团队';
            item.role = getRole(item['role']);
            item.status = getSignStatus(item['status']);
            item.type = getSignType(item['type']);
            this.practice.table.detailsTableData.push(item);
            if ( prev && prev.baseName == item.baseName && prev.name == item.name && prev.role == item.role ) {
              item.stripe = stripe;
            } else {
              stripe = !stripe;
              item.stripe = stripe;
            }
            prev = item;
          });
        })
      },

      showReservationDetailsByDay(date) {
        let params = {
          date: new Date(date).toJSON(),
          oid: this.curtOid,
          schoolAreas: this.userAreaCodes
        }

        this.reservation.table.detailsTableData = [];
        this.reservation.table.detailsViewDate = date;
        this.reservation.table.detailsVisible = true;
        getReservationDetails(params).then(resp => {
          resp.data.forEach(item => {
            this.reservation.table.detailsTableData.push(item);
            item.isTeam = (item.role == 'student' && item.count == 1) ? '个人' : '团队';
            item.startTime = toYMD_HM(item.startTime);
            item.endTime = toYMD_HM(item.endTime);
            item.createdAt = toYMD_HM(item.createdAt);
            item.role = getRole(item.role);
            item.status = getReservationStatus(item.status);
          });
        })
      },

      showReservationDetails(reservationId) {
        this.reservation.details.detailsVisible = true;
        this.reservation.details.data = [];
        getTeamsByReservationId(reservationId).then(resp => {
          resp.data.forEach(item => {
            this.reservation.details.data.push(item);
            item.role = getRole(item.role);
            item.signInTime = toYMD_HM(item.signInTime);
            item.signOutTime = toYMD_HM(item.signOutTime);
            item.patchInTime = toYMD_HM(item.patchInTime);
            item.patchOutTime = toYMD_HM(item.patchOutTime);
            item.signInStatus = getSignStatus(item.signInStatus);
            item.signOutStatus = getSignStatus(item.signOutStatus);
          });
        });
      },

      getTimeParams() {
        if ( this.params ) {
          return {
            startTime: this.params.dateRange[0],
            endTime: this.params.dateRange[1]
          }
        }
        return {
          startTime: null,
          endTime: null
        }
      },

      getPageParams(page) {
        return {
          page_no: page.currentPage,
          per_page: page.pageSize,
        }
      },

      fillBaseSummary() {
        let params = {
          ...this.getTimeParams(),
          ...this.getPageParams(this.summary.page),
          addressCodes:this.userAreaCodes
        }

        this.summary.table.data = [];
        getSchoolSummary(params).then(resp => {
          this.summary.page.total = resp.data.total;
          resp.data.rows.forEach(item => this.summary.table.data.push(item));
        });
      },

      fillPractice() {
        this.practice.table.loading = true;
        this.practice.table.data = [];

        let tmp = this.getTimeParams();
        let params = {
          dates: getDays(tmp.startTime, tmp.endTime),
          oid: this.curtOid,
          schoolAreas: this.userAreaCodes
        }

        getPracticeByDate(params).then(resp => {
          resp.data.filter(item => {
            for(const k in item)
              if ( k != 'date' && item[k] != 0 )
                return true;
            return false;
          }).forEach(item => {
            item.dateStr = toYMD(item.date);
            this.practice.table.data.push(item);
          })

          this.practice.table.loading = false;
        });
      },

      fillReservation() {
        let tmp = this.getTimeParams();

        let params = {
          dates: getDays(tmp.startTime, tmp.endTime),
          oid: this.curtOid,
          schoolAreas: this.userAreaCodes
        }

        this.reservation.table.data = [];
        this.reservation.table.loading = true;
        getReservationStatistics(params).then(resp => {
          resp.data.forEach(item => {
            item.dateStr = toYMD(item.date);
            this.reservation.table.data.push(item);
          });

          this.reservation.table.data = this.reservation.table.data.filter(item => {
            for(const k in item) {
              if ( typeof item[k] == 'number' && item[k] != 0 )
                return true;
            }
            return false;
          })
          this.reservation.table.loading = false;
        });
      },

      fillSchool() {
        if ( this.schools.data.length == 0 ) {
          getSchoolByAreaCodes(this.userAreaCodes).then(resp => {
            resp.data.forEach(item => this.schools.data.push(item))
          });
        }
      }
    },

    mounted() {
      this.fillBaseSummary();
    }
  }
</script>

<style scoped>

  #body {
    margin: 30px;
  }

  .margin-20 {
    margin: 20px;
  }

  .margin-top-20 {
    margin-top: 20px;
  }

  .padding-20 {
    padding: 20px;
  }

  .padding-top-25px {
    padding-top: 25px;
  }

  /deep/ .el-table .f2f6fc {
    background-color: #f2f6fc;
  }

</style>
